<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地图床</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        h1 {
            text-align: center;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* 用户视图样式 */
        #user-view {
            display: none;
        }

        .image-gallery {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
        }

        .image-item {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 15px;
            text-align: center;
            transition: transform 0.2s;
            width: 220px;
        }

        .image-item:hover {
            transform: scale(1.03);
        }

        .image-item img {
            max-width: 100%;
            max-height: 180px;
            object-fit: contain;
            border-radius: 5px;
            cursor: pointer;
        }

        /* 管理员视图样式 */
        #admin-view {
            display: none;
        }

        .auth-form, .upload-form {
            max-width: 400px;
            margin: 0 auto 40px;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        input[type="text"], 
        input[type="password"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        button {
            padding: 10px 20px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #2980b9;
        }

        .error {
            color: #e74c3c;
            margin-top: 15px;
        }

        .message {
            margin-top: 15px;
            color: #27ae60;
        }

        .nav-bar {
            text-align: center;
            margin-bottom: 30px;
        }

        .nav-bar button {
            margin: 0 10px;
            padding: 10px 20px;
            font-size: 16px;
        }

        .loading {
            text-align: center;
            margin-top: 30px;
            font-size: 18px;
        }

        .no-images {
            text-align: center;
            margin-top: 30px;
            font-size: 18px;
            color: #7f8c8d;
        }

        .admin-actions {
            margin-top: 40px;
        }

        .image-list {
            margin-top: 30px;
        }

        .image-info {
            margin-top: 10px;
            font-size: 14px;
        }

        .delete-btn {
            background-color: #e74c3c;
            margin-top: 10px;
        }

        .delete-btn:hover {
            background-color: #c0392b;
        }

        @media (max-width: 768px) {
            .image-item {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>本地图床</h1>
        
        <div class="nav-bar">
            <button onclick="showView('user-view')">用户视图</button>
            <button onclick="showView('admin-view')">管理员视图</button>
        </div>

        <!-- 用户视图 -->
        <div id="user-view">
            <h2>图片浏览</h2>
            
            <div class="loading" id="user-loading">
                加载中...
            </div>
            
            <div id="user-error" class="error"></div>
            
            <div class="image-gallery" id="image-gallery">
                <!-- 图片项将通过JavaScript动态添加 -->
            </div>
        </div>

        <!-- 管理员视图 -->
        <div id="admin-view">
            <!-- 登录表单 -->
            <div id="login-form" class="auth-form">
                <h2>管理员登录</h2>
                <div class="form-group">
                    <label for="username">用户名:</label>
                    <input type="text" id="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码:</label>
                    <input type="password" id="password" required>
                </div>
                <button type="button" onclick="login()">登录</button>
                <div id="admin-error" class="error"></div>
            </div>
            
            <!-- 上传表单和图片列表 -->
            <div id="admin-content">
                <!-- 上传表单 -->
                <div class="upload-form">
                    <h2>上传图片</h2>
                    <div class="form-group">
                        <input type="file" id="file-input" accept="image/*" required>
                    </div>
                    <button type="button" onclick="uploadImage()">上传</button>
                    <div id="upload-message" class="message"></div>
                </div>
                
                <!-- 图片列表 -->
                <div class="admin-actions">
                    <h2>图片列表</h2>
                    
                    <div class="loading" id="admin-loading">
                        加载中...
                    </div>
                    
                    <div id="admin-error" class="error"></div>
                    
                    <div class="no-images" id="no-images">
                        暂无图片
                    </div>
                    
                    <div class="image-list" id="admin-image-list">
                        <!-- 图片项将通过JavaScript动态添加 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 存储认证信息
        let auth = null;
        
        // 显示特定视图
        function showView(viewId) {
            document.querySelectorAll('[id$="-view"]').forEach(view => {
                view.style.display = view.id === viewId ? 'block' : 'none';
            });
            
            // 如果切换到管理员视图且已认证，则刷新图片列表
            if (viewId === 'admin-view' && auth) {
                fetchImages();
            }
        }
        
        // 格式化文件大小
        function formatFileSize(size) {
            if (size === 0) return '未知';
            const i = Math.floor(Math.log(size) / Math.log(1024));
            return (size / Math.pow(1024, i)).toFixed(2) + ' ' + ['B', 'KB', 'MB', 'GB'][i];
        }
        
        // 获取所有图片
        async function fetchImages() {
            const loadingEl = document.getElementById('user-loading');
            const errorEl = document.getElementById('user-error');
            const galleryEl = document.getElementById('image-gallery');
            
            // 显示加载状态
            loadingEl.style.display = 'block';
            errorEl.style.display = 'none';
            galleryEl.innerHTML = '';
            
            try {
                const response = await fetch('http://localhost:5000/api/images');
                if (!response.ok) {
                    throw new Error('无法获取图片列表');
                }
                
                const images = await response.json();
                
                // 隐藏加载状态
                loadingEl.style.display = 'none';
                
                // 显示提示信息（如果没有图片）
                if (images.length === 0) {
                    document.getElementById('no-images').style.display = 'block';
                } else {
                    document.getElementById('no-images').style.display = 'none';
                }
                
                // 渲染图片项
                images.forEach(image => {
                    const item = document.createElement('div');
                    item.className = 'image-item';
                    
                    item.innerHTML = `
                        <img src="${image.thumbnail_url}" alt="Image" onclick="viewImage('${image.url}')">
                        <div class="image-info">
                            <p>${image.filename}</p>
                            <p>大小: ${formatFileSize(image.size)}</p>
                        </div>
                    `;
                    
                    galleryEl.appendChild(item);
                });
                
                // 更新管理员视图中的图片列表
                updateAdminImageList(images);
            } catch (error) {
                // 显示错误信息
                loadingEl.style.display = 'none';
                errorEl.style.display = 'block';
                errorEl.textContent = '加载图片失败，请稍后再试';
                console.error('Error fetching images:', error);
            }
        }
        
        // 查看完整图片
        function viewImage(url) {
            window.open(url, '_blank');
        }
        
        // 管理员登录
        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const errorEl = document.getElementById('admin-error');
            
            errorEl.style.display = 'none';
            
            if (!username || !password) {
                errorEl.textContent = '请输入用户名和密码';
                errorEl.style.display = 'block';
                return;
            }
            
            try {
                const response = await fetch('http://localhost:5000/api/login', {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Basic ' + btoa(username + ':' + password)
                    }
                });
                
                if (response.ok) {
                    auth = { username, password };
                    document.getElementById('login-form').style.display = 'none';
                    document.getElementById('admin-content').style.display = 'block';
                    fetchImages();
                } else if (response.status === 401) {
                // 显式处理未授权的情况
                errorEl.textContent = '登录失败：用户名或密码错误';
                errorEl.style.display = 'block';
                } else {
                // 处理其他HTTP错误
                errorEl.textContent = `登录失败：服务器返回错误 ${response.status}`;
                errorEl.style.display = 'block';
                }
            } catch (error) {
                errorEl.textContent = '登录失败：无法连接到服务器，请确认后端正在运行';
                errorEl.style.display = 'block';
                console.error('Login error:', error);
            }
        }
        
        // 上传图片
        async function uploadImage() {
            const fileInput = document.getElementById('file-input');
            const messageEl = document.getElementById('upload-message');
            const errorEl = document.getElementById('admin-error');
            
            if (!auth) {
                errorEl.textContent = '请先登录管理员账户';
                errorEl.style.display = 'block';
                return;
            }
            
            if (!fileInput.files.length) {
                errorEl.textContent = '请选择要上传的文件';
                errorEl.style.display = 'block';
                return;
            }
            
            const file = fileInput.files[0];
            const formData = new FormData();
            formData.append('file', file);
            
            messageEl.style.display = 'none';
            errorEl.style.display = 'none';
            
            try {
                const response = await fetch('http://localhost:5000/api/upload', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': 'Basic ' + btoa(auth.username + ':' + auth.password)
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    
                    // 添加新图片到列表
                    const images = [{
                        filename: result.filename,
                        url: result.url,
                        thumbnail_url: result.thumbnail_url,
                        size: 0 // 服务器不会返回大小，这里设为0，稍后会从列表中更新
                    }];
                    
                    updateAdminImageList(images.concat(await getImages()));
                    
                    // 显示成功消息
                    messageEl.textContent = '图片上传成功';
                    messageEl.style.display = 'block';
                    
                    // 清空文件输入
                    fileInput.value = '';
                    
                    // 重置消息
                    setTimeout(() => {
                        messageEl.style.display = 'none';
                    }, 3000);
                } else if (response.status === 401) {
                // 显式处理未授权的情况
                errorEl.textContent = '上传失败：认证已过期，请重新登录';
                errorEl.style.display = 'block';
                // 清除无效的认证信息
                auth = null;
                document.getElementById('admin-content').style.display = 'none';
                document.getElementById('login-form').style.display = 'block';
                } else if (response.status === 413) {
                // 处理请求实体过大（通常用于大文件上传）
                errorEl.textContent = '上传失败：文件太大';
                errorEl.style.display = 'block';
                } else {
                // 处理其他HTTP错误
                errorEl.textContent = `上传失败：服务器返回错误 ${response.status}`;
                errorEl.style.display = 'block';
                }
            } catch (error) {
                errorEl.textContent = '上传失败：无法连接到服务器，请确认后端正在运行';
                errorEl.style.display = 'block';
                console.error('Upload error:', error);
            }
        }
        
        // 获取图片列表
        async function getImages() {
            try {
                const response = await fetch('http://localhost:5000/api/images', {
                    headers: {
                        'Authorization': 'Basic ' + btoa(auth.username + ':' + auth.password)
                    }
                });
                
                if (response.ok) {
                    return await response.json();
                } else {
                    throw new Error('无法获取图片列表');
                }
            } catch (error) {
                console.error('Error fetching images:', error);
                return [];
            }
        }
        
        // 更新管理员视图中的图片列表
        function updateAdminImageList(images) {
            const adminImageList = document.getElementById('admin-image-list');
            const loadingEl = document.getElementById('admin-loading');
            
            // 隐藏加载状态
            loadingEl.style.display = 'none';
            
            // 清空现有内容
            adminImageList.innerHTML = '';
            
            // 显示提示信息（如果没有图片）
            if (images.length === 0) {
                document.getElementById('no-images').style.display = 'block';
            } else {
                document.getElementById('no-images').style.display = 'none';
            }
            
            // 渲染图片项
            images.forEach(image => {
                const item = document.createElement('div');
                item.className = 'image-item';
                
                item.innerHTML = `
                    <img src="${image.thumbnail_url}" alt="Image" onclick="viewImage('${image.url}')">
                    <div class="image-info">
                        <p>${image.filename}</p>
                        <p>大小: ${formatFileSize(image.size)}</p>
                    </div>
                    <button class="delete-btn" onclick="deleteImage('${image.filename}')">删除</button>
                `;
                
                // 添加点击事件以显示图片详细信息
                item.querySelector('img').addEventListener('click', () => {
                    viewImage(image.url);
                });
                
                adminImageList.appendChild(item);
            });
        }
        
        // 删除图片
        async function deleteImage(filename) {
            if (!confirm(`确定要删除图片 ${filename} 吗？`)) {
                return;
            }
            
            const errorEl = document.getElementById('admin-error');
            errorEl.style.display = 'none';
            
            try {
                const response = await fetch(`http://localhost:5000/api/images/${filename}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': 'Basic ' + btoa(auth.username + ':' + auth.password)
                    }
                });
                
                if (response.ok) {
                    alert('图片删除成功');
                    fetchImages();
                } else {
                    alert('图片删除失败');
                }
            } catch (error) {
                alert('图片删除失败');
                errorEl.textContent = '删除图片时发生错误';
                errorEl.style.display = 'block';
                console.error('Delete error:', error);
            }
        }
        
        // 页面加载时获取图片列表
        window.addEventListener('load', fetchImages);
    </script>
</body>
</html>